import React, { useRef } from "react";
import { login } from "../../api";
import "./Login.css";
import { useNavigate } from "react-router";

const Login = () => {
    const nameInputRef = useRef();
    const navigate = useNavigate();
    const handleInputKeyUp = ({ key }) => {//回车键登录
        if (key === "Enter") handleLogin();
    };
    const handleLogin = async () => {//登录
        const { value } = nameInputRef.current;
        if (!value) return alert("请输入用户名");
        try {
            await login({ username: value });
            navigate("/");
        } catch (msg) {
            alert(msg);
        }
    };
    const initStore = () => {//重设本地存储数据
        if (window.confirm("确认重设本地存储数据吗？")) {
            localStorage.clear();
        }
    };
    return (
        <div className="loginWrapper">
            <div className="card">
                <div className="loginForm">
                    <div>Login</div>
                    <input onKeyUp={handleInputKeyUp} ref={nameInputRef} placeholder="input username(Tom or Mary)" type="text" />
                    <div className="button" onClick={handleLogin}>
                        login
                    </div>
                </div>
                <div className="authorInfo">
                    <div onClick={initStore}>范佳东</div>
                    <a href="tel:17607101164">+86 17607101164</a>
                    <a href="mailto:vansir@foxmail.com">vansir@foxmail.com</a>
                </div>
            </div>
        </div>
    );
};

export default Login;
